package TestDemo;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

public class TestDemo1 {

    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要搜索的目录");
        String rootPath = scanner.next();
        File rootFile = new File(rootPath);
        if (!rootFile.exists()) {
            System.out.println("要扫描的目录不存在");
            return;
        }
        if (!rootFile.isDirectory()) {
            System.out.println("要扫描的不是目录");
            return;
        }

        System.out.println("请输入要扫描的关键字");
        String toFind = scanner.next();

        scanDir(rootFile, toFind);
    }

    public static void scanDir(File rootFile, String toFind) throws IOException {
        File[] files = rootFile.listFiles();

        if (files == null) {
            return;
        }

        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                scanDir(files[i], toFind);
            } else {
                tryFindInFile(files[i], toFind);
            }
        }
    }

    public static void tryFindInFile(File file, String toFind) throws IOException {
        if (file.getName().contains(toFind)) {
            System.out.println("找到文件名匹配的文件: " + file.getCanonicalPath());
            return;
        }

        try (InputStream inputStream = new FileInputStream(file)) {
            StringBuilder stringBuilder = new StringBuilder();
            Scanner scanner = new Scanner(inputStream);
            while (scanner.hasNextLine()) {
                stringBuilder.append(scanner.nextLine());
            }

            if (stringBuilder.indexOf(toFind) >= 0) {
                System.out.println("找到文件内容匹配的文件: " + file.getCanonicalPath());
                return;
            }
        }
    }
}
